package com.help10000.rms.common

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration

/**
 * Created by justkeepmoving on 2017/8/4.
 */
class GridSpacingItemDecoration(private val spacing: Int, private val includeEdge: Boolean) :
    ItemDecoration() {
    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        if (parent.layoutManager !is GridLayoutManager) {
            return
        }
        val position = parent.getChildAdapterPosition(view)
        val gridLayoutManager = parent.layoutManager as GridLayoutManager?
        val spanCount = gridLayoutManager!!.spanCount
        val spanSize = gridLayoutManager.spanSizeLookup.getSpanSize(position)
        if (spanSize > 1) {
            //不是正常的布局则跳过
            return
        }
        val params = view.layoutParams as GridLayoutManager.LayoutParams
        val column = params.spanIndex
        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount
            outRect.right = (column + 1) * spacing / spanCount
            outRect.bottom = spacing
        } else {
            outRect.left = spacing - column * spacing / spanCount
            outRect.right = (column + 1) * spacing / spanCount
            outRect.top = spacing
        }
    }
}